package com.weitu.contractor.controller;

import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.StaffTrain;
import com.weitu.contractor.entity.StaffTrainCriteria;
import com.weitu.contractor.entity.TraineeCriteria;
import com.weitu.contractor.service.StaffTrainService;
import com.weitu.contractor.service.TraineeService;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.permission.user.entity.User;
import com.weitu.permission.user.service.UserService;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/4/27
 */
@Controller
@RequestMapping(value = "contractor/staffTrain")
public class StaffTrainController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "contractor/staffTrain";
    private final StaffTrainService staffTrainService;
    private final TraineeService traineeService;
    private final UserService userService;
    private final DataAuthorityService dataAuthorityService;
    private final AccessoryUtilService accessoryUtilService;

    @Autowired
    public StaffTrainController(StaffTrainService staffTrainService
            , TraineeService traineeService
            , UserService userService
            , DataAuthorityService dataAuthorityService
            , AccessoryUtilService accessoryUtilService) {
        this.staffTrainService = staffTrainService;
        this.traineeService = traineeService;
        this.userService = userService;
        this.dataAuthorityService = dataAuthorityService;
        this.accessoryUtilService = accessoryUtilService;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("uploadUserId", getSessionUser().getId());
        return MODULE_BATH_PATH + "/add";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/copy", method = RequestMethod.GET)
    public String copy(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) throws Exception {
        StaffTrainCriteria staffTrainCriteria = new StaffTrainCriteria();
        StaffTrainCriteria.Criteria criteria = staffTrainCriteria.createCriteria().andDelStateEqualTo(0);
        putSearchCriteria(criteria);

        int count = staffTrainService.countByCriteria(staffTrainCriteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            staffTrainCriteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        staffTrainCriteria.setPageView(pageView);

        List<StaffTrain> staffTrains = staffTrainService.selectByCriteria(staffTrainCriteria);
        for (StaffTrain staffTrain : staffTrains) {
            if (StringUtils.isNotEmpty(staffTrain.getTeacherId())) {
                String[] ids = staffTrain.getTeacherId().split(",");
                List<User> users = userService.selectUsersByIds(ids);
                staffTrain.setTeacherList(users);
            }
        }

        return dataGridPagination.flushDataGridData(staffTrains);
    }

    @SystemLog(module = "施工人员培训", methods = "新增施工人员培训记录")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Transactional
    public AjaxResult addAjax(StaffTrain staffTrain) throws Exception {
        String id = IDGenerator.getId();
        staffTrain.setId(id);
        staffTrain.setAddUserId(getSessionUser().getId());
        staffTrain.setAddDeptId(getSessionUser().getDepartment().getId());
        staffTrain.setAddTime(DateTimeUtil.formatterDateTime());
        staffTrain.setTrainNum(0);
        staffTrain.setQualifiedNum(0);

        if (AccessoryUtil.saveAccerssoryInfo(id)) {
            if (staffTrainService.insertSelective(staffTrain) > 0) {
                return success("保存成功！", staffTrain);
            }
            return fail("保存失败！");
        }
        return fail("附件信息保存失败！");
    }

    @SystemLog(module = "施工人员培训", methods = "更新施工人员培训记录")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @Transactional
    public AjaxResult editAjax(StaffTrain staffTrain) throws Exception {
        staffTrain.setUpdateUserId(getSessionUser().getId());
        staffTrain.setUpdateDeptId(getSessionUser().getDepartment().getId());
        staffTrain.setUpdateTime(DateTimeUtil.formatterDateTime());
        TraineeCriteria traineeCriteria = new TraineeCriteria();
        TraineeCriteria.Criteria criteria = traineeCriteria.createCriteria()
                .andDelStateEqualTo(0)
                .andTrainIdEqualTo(staffTrain.getId());

        int trainNum = traineeService.countByCriteria(traineeCriteria);
        criteria.andIsQualifiedEqualTo(1);
        int qualifiedNum = traineeService.countByCriteria(traineeCriteria);

        staffTrain.setTrainNum(trainNum);
        staffTrain.setQualifiedNum(qualifiedNum);

        if (AccessoryUtil.saveAccerssoryInfo(staffTrain.getId())) {
            if (staffTrainService.updateByPrimaryKeySelective(staffTrain) > 0) {
                return success("保存成功！", staffTrain);
            }
            return fail("保存失败！");
        }
        return fail("附件信息保存失败！");
    }

    @SystemLog(module = "施工人员培训", methods = "删除施工人员培训记录")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) throws Exception {
        if (staffTrainService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        } else {
            return fail("删除失败！");
        }
    }

    /**
     * 向页面实体添加属性
     *
     * @param model 页面实体
     * @param id    主键id
     */
    private void putModelAttributes(Model model, String id) {
        StaffTrain staffTrain = staffTrainService.selectByPrimaryKey(id);
        StringBuilder teacherNames = new StringBuilder();
        StringBuilder teacherIds = new StringBuilder();
        if (StringUtils.isNotEmpty(staffTrain.getTeacherId())) {
            String[] ids = staffTrain.getTeacherId().split(",");
            List<User> users = userService.selectUsersByIds(ids);

            for (User user : users) {
                teacherNames.append(",").append(user.getRealName());
                teacherIds.append(",").append(user.getId());
            }
        }
        model.addAttribute("accessoryList", accessoryUtilService.queryAccessoryByBusinessId(id));
        model.addAttribute("staffTrain", staffTrain);
        model.addAttribute("teacherNames", teacherNames.substring(1));
        model.addAttribute("teacherIds", teacherIds.substring(1));
        model.addAttribute("loginUserId", getSessionUser().getId());
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(StaffTrainCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("name"))) {
            criteria.andNameLike("%" + getPara("name") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("trainTypeId"))) {
            criteria.andTrainTypeIdEqualTo(getPara("trainTypeId"));
        }
        if (StringUtils.isNotEmpty(getPara("teacherId"))) {
            criteria.andTeacherIdLike("%" + getPara("teacherId") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("teacherNameOutside"))) {
            criteria.andTeacherNameOutsideLike("%" + getPara("teacherNameOutside") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("year"))) {
            criteria.andYearEqualTo(getParaToInt("year"));
        }
        if (StringUtils.isNotEmpty(getPara("trainStartTimeMin"))) {
            criteria.andTrainStartTimeGreaterThanOrEqualTo(getPara("trainStartTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("trainStartTimeMax"))) {
            criteria.andTrainStartTimeLessThanOrEqualTo(getPara("trainStartTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }
}
